/*
 *
 * 通用工具方法
 */
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
// import { Notify } from 'vant';
window.timer = null;
let timerId = 1; // 模拟计时器id，唯一性
let timerObj = {};
export default {
  // 时间戳格式化为时间
  doDayFormat (time, format) {
    if ((time + '').length === 10) {
      time = Number(time) * 1000;
    } else {
      time = Number(time);
    }
    dayjs.extend(relativeTime);
    if (typeof format === 'boolean') {
      dayjs(time).toNow();
    } else {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  // 视频格式化时长
  MillisecondToDate (msd) {
    let time = msd;
    console.log(time);
    if (time !== null && time !== '') {
      if (time >= 60 && time < 60 * 60) {
        let minute = parseInt(time / 60.0) + '';
        let second = parseInt((parseFloat(time / 60.0) - parseInt(time / 60.0)) * 60) + '';
        time = minute.padStart(2, '0') + ':' + second.padStart(2, '0');
      } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
        let hour = parseInt(time / 3600.0) + '';
        let minute = parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) + '';
        let second = parseInt((parseFloat((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60) -
          parseInt((parseFloat(time / 3600.0) - parseInt(time / 3600.0)) * 60)) * 60) + '';
        time = hour.padStart(2, '0') + ':' + minute.padStart(2, '0') + ':' + second.padStart(2, '0');
      } else {
        let temp = parseInt(time) + '';
        time = temp.padStart(5, '00:00');
      }
    } else {
      time = '00:00';
    }
    return time;
  },
  // 将图片路径转换为base64
  getBase64Image (img) {
    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
    var dataURL = canvas.toDataURL('image/' + ext);
    return dataURL;
  },
  // 将设计稿转成PX
  toPX (val) {
    return val / 75 * (document.body.clientWidth / 10);
  },
  devices: {
    // 判断Android
    isAndroid: () => {
      var u = navigator.userAgent;
      return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
    },
    // 判断设备为 ios
    isIos: () => {
      var u = navigator.userAgent;
      return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    },
    isWeixin () {
      const u = navigator.userAgent;
      let matched = u.match(/MicroMessenger/i);

      matched && (matched = matched.toString().toLowerCase());
      return matched === 'micromessenger';
    }
  },
  // 序列化数制
  // &id=2&vaule=3方式显示
  serialize (form) {
    var parts = [];
    for (var pair in form) {
      parts.push(pair + '=' + form[pair]);
    }
    return parts.join('&');
  },
  // 将对名转成FormData，可转数组 this.objectToFormData(obj)
  objectToFormData (obj, form, namespace) {
    var _formData = form || new FormData();
    var formKey;
    if (obj instanceof Array) {
      for (var a = 0; a < obj.length; a++) {
        if (typeof obj[a] === 'object' && !(obj[a] instanceof File)) {
          this.objectToFormData(obj[a], _formData, namespace + '[' + a + ']');
        } else {
          // 若是数组则在关键字后面加上[]
          _formData.append(namespace + '[' + a + ']', obj[a]);
        }
      }
    } else {
      for (var property in obj) {
        if (obj.hasOwnProperty(property) && obj[property]) {
          if (namespace) {
            // 若是对象，则这样
            formKey = namespace + '.' + property;
          } else {
            formKey = property;
          }
          if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
            this.objectToFormData(obj[property], _formData, formKey);
          } else {
            _formData.append(formKey, obj[property]);
          }
        }
      }
    }
    return _formData;
  },
  // 2个对象是否相等
  isObjEqual (o1, o2) {
    var props1 = Object.getOwnPropertyNames(o1);
    var props2 = Object.getOwnPropertyNames(o2);
    if (props1.length !== props2.length) {
      return false;
    }
    for (var i = 0, max = props1.length; i < max; i++) {
      var propName = props1[i];
      if (o1[propName] !== o2[propName]) {
        return false;
      }
    }
    return true;
  },
  // 保留2位小数
  toFixed (str) {
    var _str = str.replace(/\.{2,}/g, '.').replace(/[^\d.]/g, '');
    if (_str) {
      return _str.match(/^\d+(?:\.\d{0,2})?/)[0];
    } else {
      return _str;
    }
  },
  // 重写定时方法
  setInterval (cb, time) {
    var key = 'interval_' + timerId;
    timerId++;
    timerObj[timerId] = true;
    function timerFn () {
      if (!timerObj[timerId]) return;
      cb && cb();
      timerObj[key] = setTimeout(timerFn, time || 3000);
    }
    timerFn();
    return timerObj[key];
  },
  // 格式化参数
  formatKey (data) {
    let dType = Object.prototype.toString.call(data);
    if (dType === '[object Object]') {
      return this.transformKey(data);
    } else if (dType === '[object Array]') {
      return data.map(o => {
        return this.transformKey(o);
      });
    } else {
      return data;
    }
  },
  // 获取地址栏参数
  getQueryVariable (variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');
      if (pair[0] === variable) { return pair[1]; }
    }
    return false;
  },
  // 特殊字符过滤
  filtersNickName (str) {
    var strArr = str.split('');
    var result = '';
    var totalLen = 0;
    for (var idx = 0; idx < strArr.length; idx++) {
      // 超出长度,退出程序
      if (totalLen >= 16) break;
      var val = strArr[idx];
      // 英文,增加长度1
      if (/[a-zA-Z]/.test(val)) {
        totalLen = 1 + (+totalLen);
        result += val;
      } else if (/[\u4e00-\u9fa5]/.test(val)) { // 中文,增加长度2
        totalLen = 2 + (+totalLen);
        result += val;
      } else if (/[\ud800-\udfff]/.test(val)) {
        if (/[\ud800-\udfff]/.test(strArr[idx + 1])) {
          // 跳过下一个
          idx++;
        }
        // 将代理对替换为 "口"
        result += '口';
      }
    }
    return result;
  },
  // 将图片转成文件流
  dataURLtoFile (dataurl, filename) {
    var bstr = window.atob(dataurl);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    // 转换成file对象
    return new File([u8arr], filename, { type: 'jpg' });
    // 转换成成blob对象
    // return new Blob([u8arr], { type: mime });
  },
  floatObj: (function () {
    /*
     * 判断obj是否为一个整数
     */
    function isInteger (obj) {
      return Math.floor(obj) === obj;
    }
    /*
     * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
     * @param floatNum {number} 小数
     * @return {object}
     *   {times:100, num: 314}
     */
    function toInteger (floatNum) {
      var ret = { times: 1, num: 0 };
      if (isInteger(floatNum)) {
        ret.num = floatNum;
        return ret;
      }
      var strfi = floatNum + '';
      console.log(isInteger(floatNum));
      var dotPos = strfi.indexOf('.');
      var len = strfi.substr(dotPos + 1).length;
      var times = Math.pow(10, len);
      var intNum = Number(floatNum.toString().replace('.', ''));
      ret.times = times;
      ret.num = intNum;
      return ret;
    }
    function operation (a, b, op) {
      var o1 = toInteger(a);
      var o2 = toInteger(b);
      var n1 = o1.num;
      var n2 = o2.num;
      var t1 = o1.times;
      var t2 = o2.times;
      var max = t1 > t2 ? t1 : t2;
      var result = null;
      switch (op) {
        case 'add':
          if (t1 === t2) { // 两个小数位数相同
            result = n1 + n2;
          } else if (t1 > t2) { // o1 小数位 大于 o2
            result = n1 + n2 * (t1 / t2);
          } else { // o1 小数位 小于 o2
            result = n1 * (t2 / t1) + n2;
          }
          return result / max;
        case 'sub':
          if (t1 === t2) {
            result = n1 - n2;
          } else if (t1 > t2) {
            result = n1 - n2 * (t1 / t2);
          } else {
            result = n1 * (t2 / t1) - n2;
          }
          return result / max;
        case 'mul':
          result = (n1 * n2) / (t1 * t2);
          return result;
        case 'div':
          result = (n1 / n2) * (t2 / t1);
          return result;
      }
    }
    // 加减乘除的四个接口
    function add (a, b) {
      return operation(a, b, 'add');
    }
    function sub (a, b) {
      return operation(a, b, 'sub');
    }
    function mul (a, b) {
      return operation(a, b, 'mul');
    }
    function div (a, b) {
      return operation(a, b, 'div');
    }
    // exports
    return {
      add,
      sub,
      mul,
      div
    };
  }())

};
